package thenewscats;

import java.util.Collections;
import java.util.List;

import utilities.PMF;
import javax.jdo.PersistenceManager; 
import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;

/**
 * Factory provides methods from which to manipulate Article objects
 * within the data store within the Persistence Manager
 * 
 * @author Chris Kwok
 */
public class ArticleFactory {
	private static ArticleFactory instance;
	
	private ArticleFactory(){
		// singleton
	}
	
	/**
	 * @return an instance of the CourseFactory
	 */
	public static ArticleFactory getInstance(){
		if (instance == null){
			instance = new ArticleFactory();
		}
		return instance;
	}
	
	public boolean saveArticle (Article a){
		boolean success = true;
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
            pm.makePersistent(a);
        } catch (Exception ex){
			success = false;
		} finally {
            pm.close();
        }		
		return success;
	}
	
	public Article getArticleByKey (Key k){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Article a, detached;
		
		try {
			// 
			 a = pm.getObjectById(Article.class, k);
			 detached = pm.detachCopy(a);
		} catch (Exception e){
			detached = null;
		} finally {
			pm.close();
		}
		
		return detached;		
	}
	
	/*
	 * Returns the list of latest articles from the given category
	 * and sorted by date
	 */
	@SuppressWarnings("unchecked")
	public List<Article> getArticleByCategory (String search_cat){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		List<Article> results = Collections.EMPTY_LIST;
		
		// Create a query that searches for all articles
		// that have category == search_cat and sorted by date
		Query q = pm.newQuery(Article.class); 
		if (!search_cat.equals("home")){
			q.setFilter("category == categoryParam");
			q.declareParameters("String categoryParam");
		}
		q.setOrdering("lastModify desc");
		
		try {					
			results = (List<Article>) q.execute(search_cat);
		} catch (Exception e){
			
		} finally {
			q.closeAll();
		}
		return results;
	}
}
